'use client';

import { useState } from 'react';
import { Alert, Snackbar } from '@mui/material';
import { useRouter } from 'next/navigation';
import { examApi } from '@/api/exams';
import ExamForm from '@/components/ExamForm';

export default function CreateExamPage() {
  const [loading, setLoading] = useState(false);
  const [snackbar, setSnackbar] = useState({ open: false, message: '', severity: 'success' });
  const router = useRouter();

  const onFinish = async (values: any) => {
    try {
      setLoading(true);
      await examApi.create(values);
      setSnackbar({ open: true, message: '创建成功', severity: 'success' });
      router.push('/exams');
    } catch (error) {
      setSnackbar({ open: true, message: '创建失败', severity: 'error' });
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="p-6">
      <div className="mb-4">
        <h1 className="text-2xl font-bold">创建考试</h1>
      </div>
      <ExamForm
        onFinish={onFinish}
        loading={loading}
        initialValues={{
          duration: 60,
          totalScore: 100,
          passingScore: 60,
        }}
        submitText="创建考试"
      />
      <Snackbar
        open={snackbar.open}
        autoHideDuration={3000}
        onClose={() => setSnackbar({ ...snackbar, open: false })}
      >
        <Alert severity={snackbar.severity as any} sx={{ width: '100%' }}>
          {snackbar.message}
        </Alert>
      </Snackbar>
    </div>
  );
}